/**
 * @description 格式化时间
 * @param time
 * @param cFormat
 * @returns {string|null}
 */
export function parseTime(time: string | number | Date, cFormat: string) {
  if (arguments.length === 0) {
    return null
  }
  const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
  let date
  if (typeof time === 'object') {
    date = time
  } else {
    if (typeof time === 'string' && /^[0-9]+$/.test(time)) {
      time = parseInt(time)
    }
    if (typeof time === 'number' && time.toString().length === 10) {
      time = time * 1000
    }
    date = new Date(time)
  }
  const formatObj: any = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay()
  }
  return format.replace(/{([ymdhisa])+}/g, (result: string | any[], key: string) => {
    let value = formatObj[key]
    if (key === 'a') {
      return ['日', '一', '二', '三', '四', '五', '六'][value]
    }
    if (result.length > 0 && value < 10) {
      value = `0${value}`
    }
    return value || 0
  })
}
/**
 * This is just a simple version of deep copy
 * Has a lot of edge cases bug
 * If you want to use a perfect deep copy, use lodash's _.cloneDeep
 * @param {Object} source
 * @returns {Object}
 */
export function deepClone(source: any) {
  if (!source && typeof source !== 'object') {
    // @ts-ignore
    throw new Error('error arguments', 'deepClone')
  }
  const targetObj: any = source.constructor === Array ? [] : {}
  Object.keys(source).forEach(keys => {
    if (source[keys] && typeof source[keys] === 'object') {
      targetObj[keys] = deepClone(source[keys])
    } else {
      targetObj[keys] = source[keys]
    }
  })
  return targetObj
}

export function getKeys(str: string) {
  const reg = /\$\{(.+?)\}/
  const reg_g = /\$\{(.+?)\}/g
  const result: any = str.match(reg_g)
  if (!result) {
    return []
  }
  const list = []
  for (let i = 0; i < result.length; i++) {
    const item = result[i]
    list.push(item.match(reg)[1])
  }
  return list
}
/**
 * @description 驼峰转-连接
 * @param str
 * @returns
 */
export function handler(str: string) {
  let tuo = ''
  const arr = str.split('')
  const newArr = arr.map(ite => {
    return ite.toUpperCase() === ite ? (ite = '-' + ite.toLowerCase()) : ite
  })
  tuo = newArr.join('')
  return tuo
}
/**
 * @description 横线转驼峰
 * @param str
 * @returns str
 */
export function dashToCamelCase(str: string): string {
  return str.replace(/-(\w)/g, (match, p1) => p1.toUpperCase())
}

/**
 * @description 驼峰转横线
 * @param str
 * @returns str
 */
export function camelToDash(str: string): string {
  return str.replace(/([A-Z])/g, '-$1').toLowerCase()
}

/**
 * @description 获取mp3时长
 * @param url
 * @returns Promise<number>
 * @date 2020-04-23
 */
export function getMP3Length(url: string): Promise<number> {
  return new Promise((rel: any) => {
    const audioContext = new (window.AudioContext || window.webkitAudioContext)()
    fetch(url)
      .then(response => response.arrayBuffer())
      .then(buffer => audioContext.decodeAudioData(buffer))
      .then(audioBuffer => {
        const duration = audioBuffer.duration
        rel(duration)
      })
      .catch(error => {
        console.error('获取MP3长度失败：', error)
      })
  })
}

/**
 * @description 时长格式转换
 * @param musicTime
 * @returns string
 * @date 2020-04-23
 */
export function formatMusicTime(musicTime: number) {
  const branch = Math.floor(musicTime / 60)
  const second = Math.floor(musicTime % 60)
  if (branch < 10 && second < 10) {
    return `0${branch}:0${second}`
  } else if (branch < 10) {
    return `0${branch}:${second}`
  } else if (second < 10) {
    return `${branch}:0${second}`
  } else {
    return `${branch}:${second}`
  }
}
/**
 * @description 金额转大写
 * @param amount
 * @returns
 */
export function getCapital(amount: any) {
  // 汉字的数字
  const cnNums = ['零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖']
  // 基本单位
  const cnIntRadice = ['', '拾', '佰', '仟']
  // 对应整数部分扩展单位
  const cnIntUnits = ['', '万', '亿', '兆']
  // 对应小数部分单位
  const cnDecUnits = ['角', '分']
  // 整数金额时后面跟的字符
  const cnInteger = ''
  // 整型完以后的单位
  const cnIntLast = '元'
  // 最大处理的数字
  const maxNum = 9999999999999998
  // 金额整数部分
  let integerNum
  // 金额小数部分
  let decimalNum
  // 输出的中文金额字符串
  let chineseStr = ''
  // 分离金额后用的数组，预定义
  let parts
  if (amount === '') {
    return ''
  }
  amount = parseFloat(amount)
  if (amount >= maxNum) {
    // 超出最大处理数字
    return ''
  }
  if (amount === 0) {
    chineseStr = cnNums[0] + cnIntLast + cnInteger
    return chineseStr
  }
  // 转换为字符串
  amount = amount.toString()
  if (amount.indexOf('.') === -1) {
    integerNum = amount

    decimalNum = ''
  } else {
    parts = amount.split('.')
    integerNum = parts[0]
    decimalNum = parts[1].substr(0, 4)
  }
  // 获取整型部分转换
  if (parseInt(integerNum, 10) > 0) {
    let zeroCount = 0
    const IntLen = integerNum.length
    for (let i = 0; i < IntLen; i++) {
      const n = integerNum.substr(i, 1)
      const p = IntLen - i - 1
      const q = p / 4
      const m = p % 4
      if (n === '0') {
        zeroCount++
      } else {
        if (zeroCount > 0) {
          chineseStr += cnNums[0]
        }
        // 归零
        zeroCount = 0
        //alert(cnNums[parseInt(n)])
        chineseStr += cnNums[parseInt(n)] + cnIntRadice[m]
      }
      if (m === 0 && zeroCount < 4) {
        chineseStr += cnIntUnits[q]
      }
    }
    chineseStr += cnIntLast
  }
  // 小数部分
  if (decimalNum !== '') {
    const decLen = decimalNum.length
    for (let i = 0; i < decLen; i++) {
      const n = decimalNum.substr(i, 1)
      if (n !== '0') {
        chineseStr += cnNums[Number(n)] + cnDecUnits[i]
      }
    }
  }
  if (chineseStr === '') {
    chineseStr += cnNums[0] + cnIntLast + cnInteger
  } else if (decimalNum === '') {
    chineseStr += cnInteger
  }
  return chineseStr
}
